import React from 'react'
import { connect } from 'react-redux';
import CountAction from '@/action/countAction';
import './index.pcss'

const sleep = time => new Promise((resolve) => {
    setTimeout(() => resolve(true), time)
})

class Count extends React.Component {
    handleAdd() {
        const { dispatch } = this.props;
        dispatch(CountAction.addCountAsync({ arg: '参数' }));
    }

    handleReduce() {
        const { dispatch } = this.props;
        dispatch(CountAction.reduceCount());
    }
    // 在组件中使用async
    async reduceAsync() {
        const { dispatch } = this.props;
        await sleep(1000);
        dispatch(CountAction.reduceCount());
    }

    render() {
        const { countData } = this.props;
        const { count } = countData;

        return (
            <div className="count">
                <span className="num">{count}</span>
                <button className="btn" onClick={() => this.handleAdd()}>+</button>
                <button className="btn" onClick={() => this.reduceAsync()}>-</button>
            </div>
        )
    }
}

const mapStateToProps = state => ({
    countData: state.countData,
})

export default connect(mapStateToProps)(Count);
